package cn.jinjimi.app.main.dialog;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.RelativeLayout;

import cn.jinjimi.base.util.URLUtil;
import cn.jinjimi.app.AccountManager;
import cn.jinjimi.app.R;
import cn.jinjimi.app.webview.WebViewJavascriptBridge;
import cn.jinjimi.app.webview.WebViewHelper;
import cn.jinjimi.app.main.widget.MyWebView;

import java.util.HashMap;
import java.util.Map;


public class AlertDialog extends Dialog implements View.OnClickListener {

    private MyWebView mWv;
    private String mLoadUrl;
    private boolean hasError = false;
    private View mError;
    private boolean loading = false;

    public AlertDialog(Context context) {
        this(context, R.style.dialog_parent_style);
    }

    public AlertDialog(Context context, int themeResId) {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_zdb_ggk);
        initView();
    }

    private void initView() {

        //fullscreen
        Window window = getWindow();
        if (window != null) {
            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
        }

        mError = findViewById(R.id.error);
        mError.findViewById(R.id.do_refresh).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!loading) {
                    showContent(mLoadUrl);
                }
            }
        });

        //setup user action listener
        //findViewById(R.id.btn_close).setOnClickListener(this);
        findViewById(R.id.rl_close).setOnClickListener(this);

        mWv = (MyWebView) findViewById(R.id.wv);
        setUpWebView(mWv);

    }

    private void showContent(String url) {

        if(mWv!=null && !TextUtils.isEmpty(url)){

            mLoadUrl = URLUtil.appendParam(url, "token", AccountManager.getInstance().getAccount().token);

            mWv.post(new Runnable() {
                @Override
                public void run() {
                    int width = mWv.getWidth();
                    int height = width / 5 * 6;
                    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) mWv.getLayoutParams();
                    lp.height = height;
                    mWv.setLayoutParams(lp);
                    mWv.postInvalidate();

                    mError.setLayoutParams(lp);
                    mError.postInvalidate();

                    Map<String, String> map = new HashMap<>();
                    map.put("width", String.valueOf(width));
                    map.put("height", String.valueOf(height));

                    hasError = false;
                    loading = true;
                    mWv.loadUrl(URLUtil.appendParam(mLoadUrl, map));
                }
            });
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event){
        if(mWv!=null){
            return mWv.onTouchEvent(event);
        }
        return super.onTouchEvent(event);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void show() {
        super.show();
    }

    public void show(String url) {

        url = URLUtil.appendParam(url, "token", AccountManager.getInstance().getAccount().token);

        if(mWv!=null && mLoadUrl!=null && !mLoadUrl.equals(url)) {
            MyWebView newWebView = getNewWebView(mWv.getLayoutParams());
            newWebView.setId(R.id.wv);

            RelativeLayout parent = ((RelativeLayout) mWv.getParent());
            parent.removeView(mWv);
            parent.addView(newWebView, 0);

            @SuppressLint("WrongViewCast") RelativeLayout.LayoutParams close = (RelativeLayout.LayoutParams) findViewById(R.id.rl_close).getLayoutParams();
            close.addRule(RelativeLayout.ABOVE, newWebView.getId());
            findViewById(R.id.rl_close).setLayoutParams(close);

            setUpWebView(newWebView);
            mWv = newWebView;
        }

        show();

        if(mWv!=null && mLoadUrl!=null && !hasError && mLoadUrl.equals(url)){
            mWv.loadUrl("javascript:onView()");
        } else {
            showContent(url);
        }
    }

    private void setUpWebView(WebView view){
        view.setBackgroundColor(Color.TRANSPARENT);
        view.setLayerType(View.LAYER_TYPE_SOFTWARE,null);

        view.setWebChromeClient(new DefaultWebChromeClient());
        view.setWebViewClient(new DefaultWebViewClient(getOwnerActivity()));

        view.setVerticalScrollBarEnabled(false);
        view.setHorizontalScrollBarEnabled(false);
        // 自适应屏幕
        view.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        view.getSettings().setLoadWithOverviewMode(true);
        view.getSettings().setJavaScriptEnabled(true);

        view.getSettings().setAllowFileAccess(true);
        view.getSettings().setAllowContentAccess(true);

        view.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式

        view.getSettings().setUserAgentString(mWv.getSettings().getUserAgentString() + WebViewHelper.getUserAgent(getContext()));
        view.getSettings().setUseWideViewPort(true);

        view.addJavascriptInterface(new MinimalJSHandler(), WebViewJavascriptBridge.JS_BRIDGE_NAME);
    }

    private MyWebView getNewWebView(ViewGroup.LayoutParams lp) {
        //setup web view
        MyWebView view = new MyWebView(getContext());
        view.setLayoutParams(lp);
        return view;
    }

    @Override
    public void onClick(View v) {
        if(mWv!=null) {
            mWv.loadUrl("javascript:onClose()");
        }
        dismiss();
    }

    public void hideWebView(){
        if(mWv!=null){
            mWv.setVisibility(View.INVISIBLE);
        }
    }

    public void showWebView(){
        if(mWv!=null){
            mWv.setVisibility(View.VISIBLE);
        }
    }

    public void showErrorView(){
        if(mError!=null){
            mError.setVisibility(View.VISIBLE);
        }
    }

    public void hideErrorView(){
        if(mError!=null){
            mError.setVisibility(View.GONE);
        }
    }

    public void onLoadError(WebView view){
        hasError = true;
        showErrorView();
        hideWebView();
    }


    private class DefaultWebChromeClient extends WebChromeClient{

    }

    private class DefaultWebViewClient extends WebViewHelper.WebViewClient {

        public DefaultWebViewClient(Activity activity) {
            super(activity);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon){
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url){
            loading = false;
            if(!hasError) {
                hideErrorView();
                showWebView();
                view.loadUrl("javascript:onView()");
            }
            super.onPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean deal = super.shouldOverrideUrlLoading(view, url);
            if(deal){
                dismiss();
            }
            return deal;
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse){
            onLoadError(view);
        }

        @TargetApi(Build.VERSION_CODES.M)
        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
            super.onReceivedError(view, request, error);
            if(request.isForMainFrame()) {
                onLoadError(view);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            onLoadError(view);
        }


    }

    private class MinimalJSHandler {
        @JavascriptInterface
        public void close(){
            dismiss();
        }
    }
}
